import { useState } from 'react';
import { useStoreContext } from '../../context';

function Header() {
  const [title, setTitle] = useState('');
  const { todosStore } = useStoreContext();
  const { add } = todosStore;

  const handleKeyUp = (e) => {
    if (e.key === 'Enter') {
      const value = e.target.value;

      if (!value || !value.trim()) return;

      add(value);

      setTitle('');
    }
  };

  return (
    <header className="header">
      <h1>todos</h1>
      <input
        className="new-todo"
        placeholder="What needs to be done?"
        autoFocus
        value={title}
        onChange={e => setTitle(e.target.value)}
        onKeyUp={handleKeyUp}
      />
    </header>
  )
}

export default Header;
